<template>
  <div class="common-page page-work-order-add" v-loading.fullscreen="loading">
    <div class="common-page__head">
      <comp-paths
        class="route"
        :paths="['/work', '/work/orders/type0', $route.fullPath]"
      ></comp-paths>
      <div class="title"></div>
    </div>
    <div class="common-page__body"></div>
    <comp-dialog title="提交事项" ref="order" @close="addOrder('end')">
      <el-form
        size="small"
        label-width="112px"
        style="margin-right: 20px"
        @submit.native.prevent
        v-if="order"
      >
        <el-form-item label="企业/项目：" required>
          <el-tag
            style="margin-right: 10px; max-width: 450px"
            disable-transitions
            v-if="order.company.id"
            >{{ order.company.name }}</el-tag
          >
          <el-button
            type="plain"
            icon="el-icon-refresh"
            @click="addOrder('order-company')"
            v-if="order.company.id"
            >更换企业/项目</el-button
          >
          <el-button
            type="plain"
            icon="el-icon-plus"
            @click="addOrder('order-company')"
            v-else
            >选择企业/项目</el-button
          >
        </el-form-item>
        <el-form-item label="问题来源：" required>
          <el-select
            v-model="wtly"
            style="width: 600px"
            placeholder="请选择"
            @change="addOrder('validate')"
          >
            <el-option key="0" label="自治区调研" value="0"></el-option>
            <el-option key="1" label="市/县调研" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="调研服务组：" required v-if="wtly === '0'">
          <el-select
            v-model="order.fwxz"
            style="width: 600px"
            placeholder="请选择"
            @change="addOrder('validate')"
          >
            <el-option key="0" label="第一组" value="第一组"></el-option>
            <el-option key="1" label="第二组" value="第二组"></el-option>
            <el-option key="2" label="第三组" value="第三组"></el-option>
            <el-option key="3" label="第四组" value="第四组"></el-option>
            <el-option key="4" label="第五组" value="第五组"></el-option>
            <el-option key="5" label="第六组" value="第六组"></el-option>
            <el-option key="6" label="第七组" value="第七组"></el-option>
            <el-option key="7" label="第八组" value="第八组"></el-option>
            <el-option key="8" label="第九组" value="第九组"></el-option>
            <el-option key="9" label="第十组" value="第十组"></el-option>
            <el-option key="10" label="第十一组" value="第十一组"></el-option>
            <el-option key="11" label="第十二组" value="第十二组"></el-option>
            <el-option key="12" label="第十三组" value="第十三组"></el-option>
            <el-option key="13" label="第十四组" value="第十四组"></el-option>
            <el-option key="14" label="第十五组" value="第十五组"></el-option>
            <el-option key="15" label="第十六组" value="第十六组"></el-option>
            <el-option key="16" label="第十七组" value="第十七组"></el-option>
            <el-option key="17" label="厅局调研" value="厅局调研"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="问题层级：" required>
          <el-select
            v-model="order.lev"
            style="width: 600px"
            placeholder="请选择"
            @change="addOrder('validate')"
          >
            <el-option key="1" label="区县级" value="1"></el-option>
            <el-option key="2" label="市级" value="2"></el-option>
            <el-option key="3" label="自治区级" value="3"></el-option>
          </el-select>
        </el-form-item>

        <!--                <el-form-item label="负责工作队：" required>-->
        <!--                    <el-select v-model="order.dept.id" style="width: 600px" placeholder="请选择" @change="addOrder('validate')">-->
        <!--                        <el-option v-for="data in order.company.depts" :key="data.id" :label="data.name" :value="data.id"></el-option>-->
        <!--                    </el-select>-->
        <!--                </el-form-item>-->
        <el-form-item label="事项标题：" required>
          <el-input
            type="textarea"
            v-model="order.title"
            style="width: 600px"
            placeholder="请输入"
            :maxlength="100"
            :rows="2"
            resize="none"
            :readonly="loading"
            @change="addOrder('validate')"
          ></el-input>
        </el-form-item>
        <el-form-item label="事项描述：" required>
          <el-input
            type="textarea"
            v-model="order.content"
            style="width: 600px"
            placeholder="请输入"
            :maxlength="1000"
            :rows="10"
            resize="none"
            :readonly="loading"
            @change="addOrder('validate')"
          ></el-input>
        </el-form-item>
        <el-form-item label="事项分类：" required>
          <div style="width: 600px">
            <el-checkbox
              v-for="tag in tags"
              :key="tag.id"
              v-model="tag.selected"
              style="margin-right: 20px"
              :label="tag.name"
              :disabled="order.tags.length >= 1 && !tag.selected"
              @change="addOrder('validate')"
            ></el-checkbox>
          </div>
        </el-form-item>
        <el-form-item label="事项附件：">
          <div style="width: 600px">
            <el-tag
              style="margin: 0 10px 10px 0"
              v-for="(file, index) in order.files"
              :key="index"
              disable-transitions
              closable
              @close="addOrder('order-file-delete', file)"
              >{{ file.name }}</el-tag
            >
          </div>
          <el-button
            type="plain"
            icon="el-icon-plus"
            @click="addOrder('order-file-upload', 'image')"
            >选择图片</el-button
          >
          <el-button
            type="plain"
            icon="el-icon-plus"
            @click="addOrder('order-file-upload', 'document')"
            >选择文档</el-button
          >
        </el-form-item>
        <el-form-item label="现场办结：">
          <el-radio-group v-model="xcbj" @change="addOrder('validate')">
            <el-radio key="0" label="0">否</el-radio>
            <el-radio key="1" label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-check"
            @click="addOrder('submit')"
            >提交</el-button
          >
          <el-button type="plain" icon="el-icon-close" @click="addOrder('end')"
            >放弃</el-button
          >
        </el-form-item>
      </el-form>
    </comp-dialog>
    <comp-dialog
      title="选择企业/项目"
      width="80vw"
      height="80vh"
      ref="companyPicker"
    >
      <comp-companys
        style="height: 100%"
        ref="companyPickerList"
        limit="dept"
        v-if="order"
      >
        <template #body="scope">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-check"
            @click.stop="addOrder('order-company', scope.data.id)"
            >选择</el-button
          >
        </template>
        <template #foot="scope">
          <el-button
            type="danger"
            size="small"
            icon="el-icon-close"
            @click="addOrder('order-company-end')"
            >放弃</el-button
          >
        </template>
      </comp-companys>
    </comp-dialog>
  </div>
</template>

<script>
import mixin from "../mixin";
import { string, int, selectFile } from "../util";
export default {
  name: "page-work-order-add",
  title: "提交事项",
  nodes: ["/menu/work"],
  childs: [],
  mixins: [mixin],
  data: () => ({
    loading: false,
    order: null,
    xcbj: "0",
    wtly: "0",
    tags: [],
  }),
  methods: {
    addOrder(action, data) {
      if (this.loading) return;
      let query = this.$route.query;
      let order = this.order;

      let tags = this.tags;
      let profile = this.profile;
      if (action === "start" || !action) {
        this.loading = true;
        this.plugins.user
          .call(async () => {
            if (tags.length > 0) {
            } else
              tags = await this.plugins.user
                .getOrderOfTags()
                .then((res) => (res.code === 0 ? res.data : []));
            return { code: 0 };
          })
          .then((res) => {
            this.loading = false;
            if (res.code === 0) {
              this.order = this.plugins.user.formatOrder();
              this.order.handler = profile;

              this.order.status = "published";
              this.tags = tags;
              this.addOrder("validate");
              this.$refs.order.init();
              if (query.companyId)
                this.addOrder("order-company", query.companyId);
            } else {
              this.plugins.modal.toast(
                "加载失败<br>" + res.code + "：" + res.msg,
                "error"
              );
            }
          });
      } else if (action === "validate") {
        let error = "";

        error = error || (order.company.id ? "" : "请先选择企业/项目！");
        order.lev = string(order.lev);
        order.fwxz = string(order.fwxz).trim();
        if (this.wtly === "0") {
          error = error || (order.fwxz ? "" : "请先选择调研服务组！");
        }
        order.title = string(order.title).trim();
        order.xcbj = string(order.xcbj).trim();
        order.wtly = string(order.wtly).trim();

        error = error || (order.title ? "" : "请先输入事项标题！");
        order.content = string(order.content).trim();
        error = error || (order.content ? "" : "请先输入事项描述！");
        order.tags = tags.filter((tag) => tag.selected);
        error = 
          error = error || (order.tags.length == 1 ? "" : "事项分类必填！");
        if (data) this.plugins.modal.toast(error, "error");
        return !error;
      } else if (action === "order-company") {
        let companyId = data;
        if (companyId) {
          this.loading = true;
          this.plugins.user.getCompany(companyId).then((res) => {
            this.loading = false;
            if (res.code === 0) {
              let company = (order.company = res.data);
              let depts = (company.depts = company.depts.filter((dept) =>
                profile.depments.some((depment) => depment.dept.id === dept.id)
              ));
              if (depts.length === 1) {
                order.dept.id = depts[0].id;
                order.dept.name = depts[0].name;
              } else {
                order.dept.id = "";
                order.dept.name = "";
              }
              this.addOrder("validate");
              this.addOrder("order-company-end");
            } else {
              order.company = this.plugins.user.formatCompany();
              order.dept.id = "";
              order.dept.name = "";
              this.addOrder("validate");
              this.addOrder("order-company-end");
              this.plugins.modal.toast(
                "加载失败<br>" + res.code + "：" + res.msg,
                "error"
              );
            }
          });
        } else {
          this.$refs.companyPicker.init();
          this.$nextTick(() => this.$refs.companyPickerList.init());
        }
      } else if (action === "order-company-end") {
        this.$refs.companyPicker.close();
      } else if (action === "order-file-upload") {
        let type = data;
        let timer = null;
        let progress = (event) =>
          (timer =
            clearTimeout(timer) ||
            setTimeout(
              () =>
                this.plugins.modal.toast(
                  "上传进度：" + event.percent + "%",
                  "info"
                ),
              200
            ));
        let upload = (type, file) => {
          this.loading = true;
          this.plugins.user.uploadFile(file, type, progress).then((res) => {
            this.loading = false;
            if (res.code === 0) {
              order.files.push(res.data);
              this.addOrder("validate");
            } else {
              this.plugins.modal.alert(
                "上传失败",
                res.code + "：" + res.msg,
                "error"
              );
            }
          });
        };
        if (type === "image")
          selectFile("image/*").then((file) => {
            if (file.size > 5 * 1048576)
              this.plugins.modal.toast(
                "图片过大，不能大于5MB哦！请重新选择。",
                "error"
              );
            else upload(type, file);
          });
        if (type === "document")
          selectFile(".xls,.xlsx,.doc,.docx,.pdf").then((file) => {
            if (file.size > 10 * 1048576)
              this.plugins.modal.toast(
                "文档过大，不能大于10MB哦！请重新选择。",
                "error"
              );
            else upload(type, file);
          });
      } else if (action === "order-file-delete") {
        let file = data;
        let index = order.files.indexOf(file);
        if (index > -1) order.files.splice(index, 1);
      } else if (action === "submit") {
        if (!this.addOrder("validate", true)) return;
        this.loading = true;
        order.xcbj = this.xcbj;
        order.wtly = this.wtly;
        // order.fwxz = this.fwxz;
        console.log(order.fwxz, "order.fwxz");
        this.plugins.user.addOrder(order).then((res) => {
          this.loading = false;
          if (res.code === 0) {
            this.plugins.modal.toast("提交成功！", "success");
            this.addOrder("end");
            this.$nextTick(() =>
              this.$router.replace("/work/order?orderId=" + res.data.id)
            );
          } else {
            this.plugins.modal.alert(
              "提交失败",
              res.code + "：" + res.msg,
              "error"
            );
          }
        });
      } else if (action === "end") {
        this.$refs.order.close();
        this.$router.back();
      }
    },
    destroy() {
      if (this.loading) return;
      return true;
    },
    init() {
      if (this.loading) return;
      this.loading = true;
      this.$root.$refs.navbar.init();
      this.plugins.user
        .call(
          async () => {
            let res = await this.plugins.user.init();
            if (res.code === 0) {
            }
            return res;
          },
          async () => {
            if (this.access(this.$route.name)) return { code: 0 };
            return this.env.xhrErrors.find((error) => error.code === 4);
          }
        )
        .then((res) => {
          this.loading = false;
          this.$root.$refs.navbar.init();
          if (res.code === 0) {
            this.addOrder();
          } else if (res.code === 2) {
            this.$root.$refs.navbar.login();
          } else {
            this.plugins.modal
              .alert("页面加载失败", res.code + "：" + res.msg, "error")
              .then(() => this.$router.replace("/work/orders/type0"));
          }
        });
    },
  },
};
</script>

<style lang="scss">
.page-work-order-add {
  overflow: hidden;
}
</style>
